<template>
  <div>
    <el-button type="primary" @click="openDialog">客户新增</el-button>

    <el-dialog :visible.sync="dialogVisible" title="客户信息" width="60%" height="60%">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="form.name" @blur="checkCustomer"></el-input>
        </el-form-item>
        <el-form-item label="客户地址" prop="address">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
        <el-form-item label="客户归属地" prop="region">
          <el-input v-model="form.region"></el-input>
        </el-form-item>
        <el-form-item label="客户联系人" prop="contactPerson">
          <el-input v-model="form.contactPerson"></el-input>
        </el-form-item>
        <el-form-item label="客户电话" prop="phone">
          <el-input v-model="form.phone1"></el-input>
        </el-form-item>
        <el-form-item label="客户经理">
          <el-input v-model="form.manager"></el-input>
        </el-form-item>
        <el-form-item label="客户经理电话" prop="manager_phone">
          <el-input v-model="form.manager_phone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCustomer">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      dialogVisible: false,
      form: {
        name: '',
        address: '',
        contactPerson: '',
        phone1: '',
        region: '',
        operator: 'operator1',
        manager: '',
        manager_phone: '',
        business_mgr: '',
        status: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入客户名称', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入客户地址', trigger: 'blur' }
        ],
        region: [
          { required: true, message: '请输入客户归属地', trigger: 'blur' }
        ],
        contactPerson: [
          //{ required: true, message: '请输入客户联系人', trigger: 'blur' }
        ],
        phone: [

          { min: 11, max: 11, message: '手机号长度必须是11位数字', trigger: 'blur' },
          { pattern: /^[0-9]{11}$/, message: '手机号必须为11位数字', trigger: 'blur' }
        ],
        manager_phone: [

          { min: 11, max: 11, message: '手机号长度必须是11位数字', trigger: 'blur' },
          { pattern: /^[0-9]{11}$/, message: '手机号必须为11位数字', trigger: 'blur' }
        ]
      },
      customerExists: false
    };
  },
  methods: {
    openDialog() {
      this.dialogVisible = true;
    },
    async checkCustomer() {
      console.log('检查客户是否存在...');

      const customerExists = await this.checkCustomerExists(this.form.name);
      this.customerExists = customerExists;
      if (customerExists) {
        // 如果客户存在，展示客户信息
        this.showCustomerInfo();
      } else {
        // 如果客户不存在，重置表单的其他字段
        this.resetForm(false); // 参数 false 表示不要重置名称字段
        this.$message({
          message: '未找到该客户，可注册',
          type: 'info'
        });
      }
    },
    async checkCustomerExists(name) {
      console.log(name);
      try {
        const response = await axios.post('/api/customer/select', name, {
          headers: {
            'Content-Type': 'text/plain'
          }
        });

        if (response.data.success == true) {
          console.log(response.data.data)
          const data = response.data.data;
          this.form.address = data.address;
          this.form.contactPerson = data.contact_person;
          this.form.region = data.region;
          this.form.phone1 = data.phone1;
          this.form.manager = data.manager;
          this.form.manager_phone = data.manager_phone;
          return true;
        } else {
          return false;
        }
      } catch (error) {
        console.error('检查客户是否存在时出错', error);
        return false;
      }
    },
    showCustomerInfo() {
      // 展示客户信息并允许修改
      this.$message({
        message: '客户已存在，可以修改信息',
        type: 'warning'
      });
    },
    resetForm(resetName = true) {
      // 重置表单
      if (resetName) {
        this.form.name = '';
      }
      this.form.address = '';
      this.form.contactPerson = '';
      this.form.phone1 = '';
      this.form.region = '';
    },
    async saveCustomer() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.customerExists) {
            // 如果是已存在的客户，则保存修改
            this.saveCustomerChanges();
          } else {
            // 如果是新客户，则保存新客户信息
            this.saveNewCustomer();
          }
        } else {
          this.$message.error('请填写所有必填项');
        }
      });
    },
    saveCustomerChanges() {
      // 保存客户修改信息逻辑
      this.form.status='修改'
      console.log(this.form)
      axios.post('/api/customer/update', this.form)
        .then(response => {
          console.log(response.data)
          if(response.data.success==ture){
            this.$message({
            message: '客户修改信息保存成功',
            type: 'success'
          });
          }
          
        })
        .catch(error => {
          this.$message({
            message: '客户修改信息保存失败',
            type: 'fail'
          })
        })

      this.dialogVisible = false;
    },
    saveNewCustomer() {
      // 保存新客户信息逻辑
      this.form.status='新建'
      axios.post("/api/customer/insert", this.form)
        .then(response => {
          console.log(response.data)
          if(response.data.success==true){
            this.$message({
            message: '客户修改信息保存成功',
            type: 'success'
          })
          }
        })
      this.$message({
        message: '新客户信息保存成功',
        type: 'success'
      });
      this.dialogVisible = false;
    }
  }
};
</script>


<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
